import React, { Component } from 'react'
import { Card, Button, Form, Input, Select, message } from 'antd';
import { connect } from "react-redux"
import { ArrowLeftOutlined } from '@ant-design/icons';
import { reqCategory, reqAddProduct, reqProdDetail,reqUpdateProduct } from "../../api/index"
import PicturesWall from './PictureWall';
import RichTextEditor from './RichTextEditor';


const { Item } = Form
const { Option } = Select;
class AddUpdate extends Component {
    state = {
        categoryList: [],
        operaType: '',
        categoryId: '',
        name: '',
        desc: '',
        price: '',
        detail: '',
        imgs: [],
        _id: ''
    }
    componentDidMount() {
        const { id } = this.props.match.params
        const { categoryList } = this.props
        if (categoryList.length) this.setState({ categoryList })
        //如果redux没有，向服务器请求分类列表
        else {
            this.getCategoryList()
        }
        //若有id，说明本页属于修改
        if (id) {
            this.setState({ operaType: 'update' })
            //【这里解决不了】：从redux里拿到商品详情放入state中，下面读取不到
            // if (productList.length) {
            //     let result = productList.find((item) => {
            //         return item._id === id
            //     })
            //     this.setState({ ...result })
            //     this.form.resetFields()

            // } else {         只能通过向服务器发请求
            this.getProductDetail(id)
            // }

        } else {
            //若无id，说明添加
            this.setState({ operaType: 'add' })
        }
    }
    //请求分类列表
    getCategoryList = async () => {
        let result = await reqCategory()
        const { status,data } = result
        if(status === 0) {
            this.setState({ categoryList: data })
        }
        
    }

    //请求商品详情
    getProductDetail = async (id) => {
        let result = await reqProdDetail(id)
        const { status, data } = result
        if (status === 0) {
            //回显商品基本信息
            this.setState({ ...data })
            //回显照片墙
            this.PicturesWall.setFileList(data.imgs)
            //回显富文本
            this.RichTextEditor.setRichText(data.detail)
        }
        /*
           【!这边是巨坑!!!!，需要注意,回显之后需要初始化表单列表】
        */
        this.form.resetFields()   //重置一组字段到 initialValues
    }


    //成功提交之后
    onFinish = (values) => {
        this.form.validateFields()
            //表单验证成功时
            .then(async () => {
                //从儿子组件获照片数组
                let imgs = this.PicturesWall.getImgArr()
                //从儿子组件获得转移好的富文本
                let detail = this.RichTextEditor.getRichText()
                const {operaType,_id} = this.state
                let result; 
                if(operaType === "add") {
                    result = await reqAddProduct({ ...values, imgs, detail })
                } else {
                    result = await reqUpdateProduct({ ...values, imgs, detail, _id })
                }
                const { status } = result
                if (status === 0) {
                    message.success('操作成功')
                    //添加成功后跳回商品列表
                    this.props.history.replace('/admin/prod_about/product')  //【严重注意】：路径前面要加“/”
                }
                else message.error('添加商品失败')
            })
            .catch(() => {
                message.warn('输入项不能为空')
            })
    };
    render() {
        const { operaType, categoryList, name, desc, price, categoryId } = this.state;
        return (
            <Card
                title={
                    <>
                        <Button onClick={this.props.history.goBack} type='link' size='large'><ArrowLeftOutlined />返回</Button>
                        <span>{operaType === 'update' ? '商品修改' : '商品添加'}</span>
                    </>
                }
            >
                <Form
                    onFinish={this.onFinish}
                    wrapperCol={{ md: 7 }}
                    ref={c => this.form = c}
                    style={{ marginTop: "30px" }}
                >
                    <Item
                        label="商品名称"
                        name="name"
                        rules={[{ required: true, message: '请输入商品名称!' }]}
                        initialValue={name || ""}
                    >
                        <Input placeholder='商品名称' />
                    </Item>
                    <Item
                        label="商品描述"
                        name="desc"
                        rules={[{ required: true, message: '请输入商品描述!' }]}
                        initialValue={desc || ""}
                    >
                        <Input placeholder='商品描述' />
                    </Item>
                    <Item
                        label="商品价格"
                        name="price"
                        rules={[{ required: true, message: '请输入商品价格!' }]}
                        initialValue={price || ""}
                    >
                        {/* 原生input标签type="number" 可以点击输入框末尾加减数字 */}
                        <Input type="number" addonBefore="￥" addonAfter="元" placeholder='商品价格' />
                    </Item>
                    <Item
                        label="商品分类"
                        name="categoryId"
                        rules={[{ required: true, message: '请选择商品分类!' }]}
                        initialValue={categoryId || ""}
                    >
                        <Select placeholder={"请选择商品分类"}>
                            <Option value="">请选择分类</Option>
                            {categoryList.map((item) => {
                                return <Option key={item._id} value={item._id}>{item.name}</Option>
                            })}
                        </Select>
                    </Item>
                    <Item
                        label="商品图片"
                        wrapperCol={{ md: 10 }}
                        style={{ marginLeft: "10px" }}
                    >
                        <PicturesWall ref={c => this.PicturesWall = c} />
                    </Item>
                    <Item
                        label="商品详情"
                        wrapperCol={{ md: 16 }}
                        style={{ marginLeft: "10px" }}
                    >
                        <RichTextEditor ref={c => this.RichTextEditor = c} />
                    </Item>

                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                </Form>
            </Card>
        )
    }
}

export default connect(
    state => ({
        categoryList: state.categoryInfo,
        productList: state.productInfo
    })
)(AddUpdate)